const App = getApp()
const db = wx.cloud.database()
const tool = require('../../../common/utils/tool.js')
// 默认头像的File ID
const defaultAvatarUrl = "cloud://carlson-yun-6gsfgex5f4754200.6361-carlson-yun-6gsfgex5f4754200-1258487737/calssAvatar/默认/moren.png"


Page({

  /**
   * 页面的初始数据
   */
  data: {
    container: null,
    show: false,
    loading: true,
    // 是否更新群数组
    setgetMyclass: 0,
    addMyclass: {
      myclassName: "",
      // 具体人群选择数组
      Crowdlist: [],
    },
    // 数据库返回来的班级数组
    Myclass: [],
    // 筛选用的临时数组
    templist: [],
    // 选中具体人数的临时数组
    tempCrowdlist: [],
    chuliArray: [],
    // 上传照片
    fileList: [],
    // 默认头像
    defaultAvatarUrl: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let getopenid = App.cache.getOpenID()
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    this.setData({
      UserInfo: UserInfo,
      getopenid
    })
    // 调用获取默认头像的方法
    this.gettempAvatar()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  // 信息部分

  // 头像
  afterRead(event) {
    const {
      file
    } = event.detail;
    console.log('获取到的临时头像', file);
    this.setData({
      fileList: file
    })
    console.log('看一看', this.data.fileList);
  },
  // 删除头像
  deleteImg(event) {
    const delIndex = event.detail.index
    const {
      fileList
    } = this.data
    fileList.splice(delIndex, 1)
    this.setData({
      fileList: fileList
    })
  },


  // 获取input的值
  // 获取input输入的值
  handleChange(e, key) {
    const {
      detail,
      currentTarget
    } = e
    console.log('detail', detail);
    console.log('currentTarget', currentTarget);
    this.setData({
      [`addMyclass.${currentTarget.id}`]: detail.value,
    })
  },



  // 选人内容
  // 展示班级人群详情
  handleCheckBoxChange: tool.throttle(
    function (e) {
      let that = this
      const {
        account
      } = e.currentTarget.dataset
      const res = that.data.tempCrowdlist.map(x => {
        x.list = x.list.map(y => {
          if (y.account == account) {
            y.checked = !y.checked
          }
          return y
        })
        return x
      })
      that.setData({
        tempCrowdlist: res
      })
      let arr = []
      that.data.tempCrowdlist.forEach(x => {
        arr = arr.concat(x.list.filter(y => y.checked))
      })
      let obj = {};
      arr = arr.reduce((cur, next) => {
        obj[next.account] ? "" : obj[next.account] = true && cur.push(next);
        return cur;
      }, []);
      console.log('要提交的:', arr)
      that.setData({
        ['addMyclass.Crowdlist']: arr
      })
    }
  ),
  // 弹窗
  showPopup() {
    this.setData({
      show: true,
    });
    if (this.data.setgetMyclass == 0) {
      // 获取所有班级数据
      this.getMyclass()
    } else {
      const arr = this.data.Myclass.map(x => {
        x.checked = true;
        return x
      })
      this.setData({
        Myclass: arr
      })
    }

  },

  onClose() {
    this.setData({
      show: false
    });
  },

  onChange(e) {
    let that = this
    console.log('已经选中的班级是：', e.detail.value)
    let list = e.detail.value
    let myclass = that.data.Myclass
    // 班级数组
    let setarr = []
    // 班级成员数组
    let member = []
    for (let k = 0; k < list.length; k++) {
      for (let i = 0; i < myclass.length; i++) {
        if (list[k] == myclass[i].myclassId) {
          setarr.push(myclass[i])
          member.push(myclass[i].list.map(x => {
            x.checked = true;
            return x
          }))
        }
      }
    }
    // 利用扁平化数组将几个数组的人合并成一个数组
    const flatten = arr =>
      arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
    let getmember = flatten(member)
    console.log('获取全部选中的人:', getmember);
    that.setData({
      // 临时班级总数组，页面要用
      tempCrowdlist: setarr,
      // 这里是传递给是否要取消选择一些同学的方法用的数组
      chuliArray: getmember,
      // 已经去重的成员数组，如果没有进行取消，这已经可以提交
      ['addMyclass.Crowdlist']: getmember
    })
  },


  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},
  // 班级选择 end


  // 搜索班级
  searchMyclass(e) {
    let key = e.detail.toLowerCase();
    console.log(key);
    let list = this.data.templist;
    let MyclassArray = []
    for (let i = 0; i < list.length; i++) {
      let listname = list[i].name.toLowerCase();
      if (listname.search(key) != -1) {
        MyclassArray.push(list[i])
      }
    }
    console.log('筛选后:', MyclassArray);
    this.setData({
      Myclass: MyclassArray
    })
  },
  // 云函数返回来的班级
  getMyclass() {
    wx.cloud.callFunction({
      name: 'getMyclass',
      complete: res => {
        console.log('云函数返回来的班级:', res.result.data)
        if (res.result.data === undefined) {
          this.setData({
            loading: false,
            setgetMyclass: 1
          })
          return
        }
        let list = res.result.data
        // 然后把管理员去除
        list.forEach(item => {
          item.list.forEach((x, idx) => {
            if (x.identityId === 'Administrator') {
              item.list.splice(idx, 1)
            }
          })
        })
        console.log('list', list);
        // 班级数组
        this.setData({
          Myclass: list,
          templist: list,
          loading: false,
          setgetMyclass: 1
        })


      }
    })
  },

  // 获取默认头像的临时路径
  gettempAvatar() {
    wx.cloud.downloadFile({
      fileID: defaultAvatarUrl,
      success: res => {
        console.log('拿到了吗', res.tempFilePath)
        this.setData({
          defaultAvatarUrl: res.tempFilePath
        })
      },
      fail: err => {
        // handle error
      }
    })
  },

  // 创建班级
  addMyclass() {
    let that = this
    let AvatarUrl = that.data.defaultAvatarUrl
    if (!that.data.addMyclass.myclassName) {
      App.toast.showToast('名称不能为空!', 'error')
      return false
    }
    // 编写getfileID() Promise函数，这个函数用于把照片的临时路径上传到云储存
    function getfileID() {
      App.toast.showLoading('创建中')
      let cloudPath = "calssAvatar/" + new Date().getTime() + ".png"
      return new Promise((resolve, reject) => {
        wx.cloud.uploadFile({
          cloudPath,
          filePath: that.data.fileList == '' ? AvatarUrl : that.data.fileList[0].url, // 头像照片文件路径
        }).then(res => {
          console.log('获取fileID', res.fileID)
          App.toast.hideLoading()
          resolve(res.fileID)
        }).catch(error => {
          console.log(error);
          App.toast.hideLoading()
        })
      })
    }
    function setAvatar(fileID) {
      App.toast.showLoading('创建中')
      console.log('获取到照片', fileID);
      let Crowdlist = that.data.addMyclass.Crowdlist
      // 获取我的信息
      let UserInfo = that.data.UserInfo
      Crowdlist.push(UserInfo)
      // 将数组中相同的人进行去重
      let newgetmember = [];
      Crowdlist.forEach((i) => {
        newgetmember.some((item) => item.account == i.account) ? '' : newgetmember.push(i);
      });
      console.log('最终提交的人群数组', newgetmember);
      let myclassId = (+new Date()).toString().substring(5, 13)
      db.collection('myclass').add({
        data: {
          list: newgetmember,
          myclassId: Number(myclassId),
          name: that.data.addMyclass.myclassName,
          calssAvatar: fileID,
          CreationTime: Date.now(),
          Administrator: UserInfo.account,
          AdministratorName: UserInfo.nickName,
          classType: UserInfo.identityId === 'Administrator' ? '专业班级' : '课程班级',
          permissions: true
        },

      }).then(res => {
        console.log(res)
        // 创建聊天社区
        db.collection('chat-msg').add({
          data: {
            coursename: '',
            courseId: '',
            calssAvatar: fileID,
            className: that.data.addMyclass.myclassName,
            classId: Number(myclassId),
            members: newgetmember,
            _openid: that.data.getopenid,
            records: [],
            ChatCommunityName: that.data.addMyclass.myclassName,
            ChatCommunityId: 'chat' + myclassId,
            Creator: {
              name: UserInfo.nickName,
              account: UserInfo.account
            },
            latestNewsTime: 0,
            chatType: "class",
            timeTs: Date.now(),
            permissions: true
          },
          success: function (res) {
            App.toast.hideLoading()
            App.toast.showToast('创建成功，即将返回我的班级')
          }
        })
        setTimeout(() => {
          that.navIndex()
        }, 1500)
      })
    }
    // 调用方法
    getfileID().then(fileID => {
      return setAvatar(fileID);
    }).catch(err => {
      console.log(err);
    })
    App.toast.hideLoading()

  },
  // 跳转回去
  navIndex() {
    // 通过判断当前页面的页面栈信息，是否有上一页进行返回
    const pages = getCurrentPages()
    if (pages.length == 1) {
      console.log('已经返回来了');
    } else {
      wx.navigateBack({
        delta: 1
      })
    }

  },

})